<template>
  <div class="code_bg" ref="codeBg">
    <div class="icon_btn">
      <a-icon class="icon_style" v-if="isChangeCopy" @click="checkCodeType" type="swap" />
      <a-icon class="icon_style" type="copy" @click="copyCode" />
    </div>
    <div
      class="code_area"
      :style="{ height: codeHeight, width: codeWidth }"
      v-if="isCommont"
      oncontextmenu="return false"
      ondragstart="return false"
      onselectstart="return false"
      onselect="document.selection.empty()"
      oncopy="document.selection.empty()"
      onbeforecopy="return false"
    >
      {{ codeObject }}
    </div>
    <pre
      class="code_area"
      :style="{ height: codeHeight, width: codeWidth }"
      style="white-space: pre"
      v-else
      oncontextmenu="return false"
      ondragstart="return false"
      onselectstart="return false"
      onselect="document.selection.empty()"
      oncopy="document.selection.empty()"
      onbeforecopy="return false"
      >{{ codeObject }}</pre
    >
  </div>
</template>

<script>
export default {
  data() {
    return {
      isCommont: true,
      codeHeight: "0px",
      codeWidth: "0px",
    };
  },
  props: {
    codeObject: {
      type: null,
      default: "",
    },
    isChangeCopy: {
      type: Boolean,
      default: true,
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.codeHeight = `${this.$refs.codeBg?.offsetHeight - 40 || 0}px`;
      this.codeWidth = `${this.$refs.codeBg?.offsetWidth - 40 || 0}px`;
    });
  },
  methods: {
    checkCodeType() {
      this.isCommont = this.isChangeCopy ? !this.isCommont : false;
    },
    copyCode() {
      let str = this.isCommont
        ? JSON.stringify(this.codeObject)
        : JSON.stringify(this.codeObject, null, 4);
      this.$copyText(str)
        .then(() => {
          this.$toast("复制成功");
        })
        .catch(() => {
          this.$toast.fail("该浏览器不支持复制");
        });
    },
  },
};
</script>

<style lang="less" scoped>
.code_bg {
  position: relative;
  display: flex;
  flex-direction: column;
  padding: 40px 20px 20px;
  box-sizing: border-box;
  height: 100%;
  width: 100%;
  border-radius: 6px;
  color: rgba(255, 255, 255, 0.8);
  background-color: rgb(15, 15, 15);
  .code_area {
    overflow-x: hidden;
    overflow-y: scroll;
  }
  .icon_btn {
    position: absolute;
    top: 20px;
    right: 20px;
    font-size: 20px;
    display: flex;
    justify-content: flex-end;

    .icon_style {
      margin-right: 14px;
      cursor: pointer;
      &:nth-last-child(1) {
        margin-right: 0;
      }
      &:hover {
        color: #fff;
      }
    }
  }
}
</style>
